package com.firemoss.ui.blanket.components
{
	import com.firemoss.ui.blanket.calloutClasses.*;
	import com.firemoss.ui.blanket.util.Orientation;
	
	import flash.utils.Dictionary;
	
	import mx.core.IMXMLObject;
	import mx.core.UIComponent;
	import mx.events.CloseEvent;
	
	[DefaultProperty("calloutContents")]
	
	[Event(name="close", type="mx.events.CloseEvent")]
	
	/**
	 * Wraps a CalloutDisplay instance to allow it to be used as an MXML component outside of
	 * display list.
	 */
	public class Callout extends AbstractOverlayComponent implements IMXMLObject
	{
		
		// STATIC
		
		/**
		 * Used to track all instances of the Callout component, powering things like Callout.hideAll()
		 */
		private static var callouts : Dictionary = new Dictionary( true )
		
		/**
		 * Hides all Callout instances.
		 */
		public static function closeAll() : void
		{
			for each ( var callout : Callout in callouts )
			{
				callout.visible = false
			}
		}
		
		// PROTECTED PROPERTIES
		
		protected function get calloutView() : AbstractCallout
		{
			return view as AbstractCallout
		}
		
		protected function get calloutViewClass() : Class
		{
			return CalloutDisplay
		}
		
		// PUBLIC PROPERTIES
		
		private var _calloutContents : UIComponent
		/**
		 * The display object to show in the callout.
		 */
		public function set calloutContents( value : UIComponent ) : void
		{
			if (calloutView)
			{
				calloutView.calloutContents = value
			}
		}   	
 	
 		public function set orientation( value : int ) : void
		{
			var priorityQueue : Array = []
			
			for ( var i : int = value; i < Orientation.defaultOrientationPriority.length + value ; i ++ )
			{
				priorityQueue.push( i < Orientation.defaultOrientationPriority.length ? i : i - Orientation.defaultOrientationPriority.length )
			}
			
			calloutView.orientationPriority = priorityQueue
		}
		public function get orientation() : int
		{
			var queue : Array = calloutView.orientationPriority
			
			if (queue.length > 0)
			{
				return queue[0]
			}
			else
			{
				return -1
			}
		}

		public function set relativeX( value : Number ) : void
		{
			if (calloutView)
			{
				calloutView.relativeX = value
			}
		}
		public function get relativeX() : Number
		{
			return calloutView ? calloutView.relativeX : NaN
		}

		public function set relativeY( value : Number ) : void
		{
			if (calloutView)
			{
				calloutView.relativeY = value
			}
		}
		public function get relativeY() : Number
		{
			return calloutView ? calloutView.relativeY : NaN
		}
		
		// CONSTRUCTOR
		
		public function Callout()
		{
			view = new calloutViewClass()
			
			view.addEventListener( CloseEvent.CLOSE, onClose, false, 0, true )
			
			Callout.callouts[ this ] = this
		} 	
		
		// EVENT LISTENERS
		
		private function onClose( event : CloseEvent ) : void
		{
			visible = false
		}
		 
	}
}